<template>
  <div class="greenhouse-info">
    <!-- 智慧大棚土壤质量实时监测 -->
    <div class="monitor-section">
      <div class="section-title">
        智慧大棚土壤质量实时监测
        <el-button 
          type="primary" 
          class="refresh-btn" 
          :loading="isLoading"
          @click="fetchNewData">
          <el-icon><Refresh /></el-icon>
          获取最新数据
        </el-button>
      </div>
      
      <div class="info-grid">
        <div class="info-item">
          <span class="label">智慧大棚编号</span>
          <span class="value">E-01</span>
        </div>
        <div class="info-item">
          <span class="label">生长阶段</span>
          <span class="value">开花结果期</span>
        </div>
        <div class="info-item">
          <span class="label">占地面积</span>
          <span class="value">0.68 亩</span>
        </div>
        <div class="info-item">
          <span class="label">土壤PH值</span>
          <span class="value">{{ monitorData.find(item => item.type === 'ph')?.value || '0' }}</span>
        </div>
      </div>

      <div class="nutrient-boxes">
        <div class="nutrient-box">
          <div class="box-left">
            <div class="box-title">土壤含磷量</div>
            <div class="box-unit">MG/KG</div>
          </div>
          <div class="box-right">
            <div class="box-value">{{ monitorData.find(item => item.type === 'phosphorus')?.value || '0' }}</div>
          </div>
        </div>
        <div class="nutrient-box">
          <div class="box-left">
            <div class="box-title">土壤含钾量</div>
            <div class="box-unit">MG/KG</div>
          </div>
          <div class="box-right">
            <div class="box-value">{{ monitorData.find(item => item.type === 'potassium')?.value || '0' }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 智慧大棚实时环境监测 -->
    <div class="monitor-section">
      <div class="section-title">
        智慧大棚土壤温度监测
      </div>
      <div class="gauge-container">
        <div class="gauge-chart" ref="tempGauge"></div>
      </div>
    </div>

    <!-- 温度检测数据统计 -->
    <div class="monitor-section">
      <div class="section-title">
        光照强度变化趋势
      </div>
      <div class="trend-chart" ref="tempTrendChart"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { 
  getSoilTemperatureData, 
  getPhData, 
  getPhosphorusData, 
  getPotassiumData, 
  getLightData,
  collectAllSoilData
} from '@/api'

const props = defineProps({
  greenhouseId: {
    type: String,
    required: true
  }
})

const greenhouseInfo = ref({})
const monitorData = ref([
  { type: 'temperature', name: '土壤温度', value: 0, unit: '°C' },
  { type: 'ph', name: '土壤pH值', value: 0, unit: '' },
  { type: 'phosphorus', name: '磷含量', value: 0, unit: 'mg/kg' },
  { type: 'potassium', name: '钾含量', value: 0, unit: 'mg/kg' },
  { type: 'light', name: '光照强度', value: 0, unit: 'lux' }
])

const activeChart = ref('temperature')
const tempChart = ref(null)
const nutrientChart = ref(null)
const lightChart = ref(null)
const statisticsChart = ref(null)
let timer = null

// 添加loading状态
const isLoading = ref(false)

// 获取最新监测数据
const fetchLatestData = async () => {
  try {
    const end = new Date()
    const start = new Date(end - 5 * 60 * 1000) // 最近5分钟的数据

    const [tempData, phData, phosphorusData, potassiumData, lightData] = await Promise.all([
      getSoilTemperatureData(start.getTime(), end.getTime()),
      getPhData(start.getTime(), end.getTime()),
      getPhosphorusData(start.getTime(), end.getTime()),
      getPotassiumData(start.getTime(), end.getTime()),
      getLightData(start.getTime(), end.getTime())
    ])

    // 更新监测数据
    updateMonitorValue('temperature', tempData)
    updateMonitorValue('ph', phData)
    updateMonitorValue('phosphorus', phosphorusData)
    updateMonitorValue('potassium', potassiumData)
    updateMonitorValue('light', lightData)
  } catch (error) {
    console.error('获取监测数据失败:', error)
  }
}

// 修改更新监测值的方法
const updateMonitorValue = (type, data) => {
  if (data && data.length > 0) {
    const item = monitorData.value.find(item => item.type === type)
    if (item) {
      item.value = data[data.length - 1].value
      // 更新仪表盘数据
      if (type === 'temperature' && tempGaugeInstance.value) {
        tempGaugeInstance.value.setOption({
          series: [{
            data: [{
              value: item.value
            }]
          }]
        })
      }
    }
  }
}

// 修改更新图表数据的方法
const updateChartData = async () => {
  try {
    const end = new Date()
    const start = new Date(end - 7 * 24 * 60 * 60 * 1000)

    const lightData = await getLightData(start.getTime(), end.getTime())
    const dailyLightData = processLightData(lightData)

    if (tempTrendChartInstance.value) {
      tempTrendChartInstance.value.setOption({
        series: [{
          data: dailyLightData
        }]
      })
    }
  } catch (error) {
    console.error('更新图表数据失败:', error)
  }
}

// 修改数据处理函数，按小时分组计算平均值
const processLightData = (data) => {
  const hourlyData = new Array(24).fill(0).map(() => ({
    sum: 0,
    count: 0
  }))
  
  data.forEach(item => {
    const date = new Date(item.createTime)
    const hour = date.getHours()
    hourlyData[hour].sum += item.value
    hourlyData[hour].count++
  })
  
  // 计算每小时的平均值
  return hourlyData.map(hour => 
    hour.count > 0 ? +(hour.sum / hour.count).toFixed(1) : 0
  )
}

// 修改图表相关的变量声明
const tempGauge = ref(null)
const tempTrendChart = ref(null)
const tempGaugeInstance = ref(null)
const tempTrendChartInstance = ref(null)

// 修改初始化仪表盘的方法
const initGauges = () => {
  if (!tempGauge.value) return null
  
  const chart = echarts.init(tempGauge.value)
  const tempOption = {
    series: [{
      type: 'gauge',
      min: 0,
      max: 30,
      splitNumber: 8,
      radius: '95%',
      axisLine: {
        lineStyle: {
          width: 8,
          color: [
            [0.3, '#67e0e3'],
            [0.7, '#37a2da'],
            [1, '#fd666d']
          ]
        }
      },
      pointer: {
        itemStyle: {
          color: '#00ffff'
        },
        width: 4
      },
      axisTick: {
        distance: -8,
        length: 6,
        lineStyle: {
          color: '#00ffff',
          width: 1
        }
      },
      splitLine: {
        distance: -8,
        length: 10,
        lineStyle: {
          color: '#00ffff',
          width: 2
        }
      },
      axisLabel: {
        color: '#00ffff',
        distance: 14,
        fontSize: 10
      },
      detail: {
        valueAnimation: true,
        formatter: '{value} °C',
        color: '#00ffff',
        fontSize: 16,
        offsetCenter: [0, '80%']
      },
      data: [{
        value: 0,
        // name: '土壤温度',
        title: {
          offsetCenter: [0, '105%'],
          fontSize: 12,
          color: '#00ffff'
        }
      }]
    }]
  }
  chart.setOption(tempOption)
  return chart
}

// 修改初始化趋势图的方法
const initTempChart = () => {
  if (!tempTrendChart.value) return null
  
  const chart = echarts.init(tempTrendChart.value)
  const option = {
    title: {
      text: '24小时光照强度变化',
      textStyle: {
        color: '#00ffff',
        fontSize: 14
      },
      top: 5,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      },
      formatter: function(params) {
        return `${params[0].axisValue}时<br/>${params[0].marker}光照强度: ${params[0].value} lux`
      }
    },
    grid: {
      top: 40,
      left: 40,
      right: 40,
      bottom: 30
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: Array.from({length: 24}, (_, i) => `${i}`.padStart(2, '0')),
      axisLine: {
        lineStyle: {
          color: '#00ffff'
        }
      },
      axisLabel: {
        color: '#00ffff',
        formatter: '{value}:00',
        fontSize: 10
      }
    },
    yAxis: {
      type: 'value',
      name: '光照强度(lux)',
      nameTextStyle: {
        color: '#00ffff',
        fontSize: 10
      },
      axisLine: {
        lineStyle: {
          color: '#00ffff'
        }
      },
      axisLabel: {
        color: '#00ffff',
        fontSize: 10
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(0, 255, 255, 0.1)'
        }
      }
    },
    series: [
      {
        name: '光照强度',
        type: 'line',
        smooth: true,
        data: new Array(24).fill(0),
        lineStyle: {
          color: '#ffd93d',
          width: 2
        },
        itemStyle: {
          color: '#ffd93d'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(255, 217, 61, 0.4)'
            },
            {
              offset: 1,
              color: 'rgba(255, 217, 61, 0.1)'
            }
          ])
        },
        symbolSize: 6
      }
    ]
  }
  chart.setOption(option)
  return chart
}

// 修改获取新数据的方法
const fetchNewData = async () => {
  if (isLoading.value) return
  
  isLoading.value = true
  try {
    console.log('开始获取新数据')
    
    // 调用后端接口收集新数据
    const response = await collectAllSoilData(props.greenhouseId)
    console.log('获取到的新数据:', response)
    
    // 检查响应格式
    if (!response || !response.data) {
      throw new Error('返回数据格式不正确')
    }
    
    // 检查数据有效性
    const hasInvalidData = Object.values(response.data).some(value => 
      value === undefined || value === null || isNaN(value)
    )
    
    if (hasInvalidData) {
      throw new Error('采集到的数据无效，请重试')
    }
    
    // 更新监测数据
    monitorData.value.forEach(item => {
      const value = response.data[item.type]
      if (value !== undefined) {
        console.log(`更新${item.name}:`, value)
        item.value = value
        
        // 如果是温度数据，更新仪表盘
        if (item.type === 'temperature' && tempGaugeInstance.value) {
          tempGaugeInstance.value.setOption({
            series: [{
              data: [{
                value: value
              }]
            }]
          })
        }
      }
    })
    
    // 更新图表
    await updateChartData()
    
    ElMessage.success(response.message || '数据更新成功')
  } catch (error) {
    console.error('获取新数据失败:', error)
    console.error('错误详情:', {
      message: error.message,
      response: error.response,
      config: error.config
    })
    
    ElMessage.error(error.message || '获取数据失败')
  } finally {
    isLoading.value = false
  }
}

onMounted(() => {
  // 初始化图表实例
  nextTick(() => {
    tempGaugeInstance.value = initGauges()
    tempTrendChartInstance.value = initTempChart()
    
    // 获取数据
    fetchLatestData()
    updateChartData()
  })

  // 定时更新
  timer = setInterval(() => {
    fetchLatestData()
    updateChartData()
  }, 60000)
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
  if (tempGaugeInstance.value) {
    tempGaugeInstance.value.dispose()
  }
  if (tempTrendChartInstance.value) {
    tempTrendChartInstance.value.dispose()
  }
})
</script>

<style scoped>
.greenhouse-info {
  height: 100%;
  background-color: #001529;
  color: #00ffff;
  padding: 10px;
  background-image: linear-gradient(45deg, rgba(0, 255, 255, 0.05) 1px, transparent 1px),
                    linear-gradient(-45deg, rgba(0, 255, 255, 0.05) 1px, transparent 1px);
  background-size: 30px 30px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  overflow: hidden;
  max-height: 100vh;
}

.monitor-section {
  margin-bottom: 10px;
  border: 1px solid #00ffff;
  border-radius: 4px;
  padding: 8px 10px;
  background: rgba(0, 21, 41, 0.8);
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: calc((100vh - 50px) / 3);
  min-height: 0;
}

.monitor-section:first-child {
  min-height: 0;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 8px;
  margin: 0;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 3px;
}

.label {
  color: rgba(0, 255, 255, 0.7);
  font-size: 12px;
  height: 16px;
  line-height: 16px;
  white-space: nowrap;
}

.value {
  color: #00ffff;
  font-size: 15px;
  font-weight: bold;
  height: 20px;
  line-height: 20px;
}

.nutrient-boxes {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  margin-top: 10px;
  flex: 1;
}

.nutrient-box {
  background: rgba(0, 255, 255, 0.05);
  border: 1px solid rgba(0, 255, 255, 0.3);
  border-radius: 8px;
  padding: 8px;
  text-align: center;
  position: relative;
  transition: all 0.3s ease;
  backdrop-filter: blur(5px);
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.nutrient-box:hover {
  transform: translateY(-2px);
  box-shadow: 0 0 15px rgba(0, 255, 255, 0.2);
  border-color: rgba(0, 255, 255, 0.5);
}

.box-left {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 2px;
}

.box-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 2px;
}

.box-title {
  color: rgba(0, 255, 255, 0.7);
  font-size: 14px;
  font-weight: 500;
  margin: 0;
}

.box-value {
  color: #00ffff;
  font-size: 24px;
  font-weight: bold;
  text-shadow: 0 0 10px rgba(0, 255, 255, 0.3);
  margin: 0;
}

.box-unit {
  color: rgba(0, 255, 255, 0.6);
  font-size: 12px;
  letter-spacing: 1px;
  margin: 0;
}

.nutrient-box::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, transparent, rgba(0, 255, 255, 0.5), transparent);
}

.nutrient-box::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, rgba(0, 255, 255, 0.3), transparent);
}

.gauge-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0;
}

.gauge-chart {
  width: 100%;
  height: 100%;
  max-width: 300px;
}

.trend-chart {
  flex: 1;
  width: 100%;
  height: calc(100% - 30px);
}

/* 添加网格背景 */
.monitor-section {
  background-image: 
    linear-gradient(rgba(0, 255, 255, 0.05) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0, 255, 255, 0.05) 1px, transparent 1px);
  background-size: 20px 20px;
}

/* 添加边角装饰 */
.monitor-section::after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 20px;
  height: 20px;
  border-top: 2px solid #00ffff;
  border-right: 2px solid #00ffff;
}

.monitor-section::before {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 20px;
  height: 20px;
  border-bottom: 2px solid #00ffff;
  border-left: 2px solid #00ffff;
}

/* 添加呼吸灯效果 */
@keyframes glow {
  0% { box-shadow: 0 0 5px rgba(0, 255, 255, 0.2); }
  50% { box-shadow: 0 0 20px rgba(0, 255, 255, 0.4); }
  100% { box-shadow: 0 0 5px rgba(0, 255, 255, 0.2); }
}

.monitor-section {
  animation: glow 3s infinite;
}

.refresh-btn {
  background: rgba(0, 255, 255, 0.1);
  border: 1px solid rgba(0, 255, 255, 0.3);
  color: #00ffff;
  padding: 4px 12px;
  height: 28px;
  font-size: 12px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 4px;
  margin: 0;
}

.refresh-btn:hover {
  background: rgba(0, 255, 255, 0.2);
  border-color: rgba(0, 255, 255, 0.5);
}

.refresh-btn:active {
  transform: scale(0.98);
}

.refresh-btn.is-loading {
  background: rgba(0, 255, 255, 0.05);
  opacity: 0.8;
}

/* 添加时间显示样式 */
.current-time {
  position: fixed;
  top: 20px;
  right: 20px;
  font-size: 20px;
  color: #00ffff;
  font-family: 'Monaco', monospace;
  text-shadow: 0 0 10px rgba(0, 255, 255, 0.3);
  z-index: 1000;
}

/* 隐藏切换大棚按钮 */
.el-button.switch-greenhouse {
  display: none;
}

.weather-section,
.weather-header,
.weather-title,
.weather-location,
.weather-time,
.weather-gauge,
.weather-info,
.weather-temp-text,
.weather-current-temp {
  display: none;
}

.section-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}
</style> 